#-*- coding:utf-8 -*-

from my_mongo import *
from entity import *
from my_redis import *
import time

class DaoBase:

    def __init__(self, colName):
        (db,con) = getMongo()
        self.db = db
        self.con = con
        self.col = self.db[colName]

    def close(self):
        closeMongo(self.con)

class ParkDao(DaoBase):

    def __init__(self):
        DaoBase.__init__(self,"park")

    def findParks(self,loc):
        ps = self.col.find({'loc':{"$near":loc}})
        parks = []
        for p in ps:
            parks.append(Park(p))
        return parks

    def get(self,pid):
        doc = self.col.find_one(ObjectId(pid));
        return Park(doc)

    def save(self, park):
        if self.col.count() == 0:
            #确保位置索引的创建
            self.col.ensure_index([('loc',pymongo.GEO2D)])

        doc = park.__dict__
        if park.pid:
            doc['_id'] = ObjectId(park.pid)
        del doc['pid']
        pid = str(self.col.save(park.__dict__))
        
        return pid

class CarDao(DaoBase):

    def __init__(self):
        DaoBase.__init__(self,'car')

    #获取某个用户的所有车
    def getCarsByUid(self,uid):
        docs = self.col.find({'uid':uid})
        cars = []
        for c in docs:
            cars.append(Car(c))
        return cars

    #保存车
    def save(self,car):
        doc = car.getDoc()
        cid = str(self.col.save(doc))
        return cid


class PicDao(DaoBase):

    PicDir = '/Users/alala/Tem/Pic/'

    def __init__(self):
        DaoBase.__init__(self,"pic")

    def save(self,pic):
        doc = pic.__dict__
        if pic.pid:
            doc['_id'] = ObjectId(pic.pid)
        del doc['pid']
        
        pid = str(self.col.save(doc))
        return pid

    def get(self, pid):
        if not ObjectId.is_valid(pid):
            return None
        p = self.col.find_one(ObjectId(pid))
        if p:
            print p['fileName']
            return Pic(p)
        else:
            print 'pic not found:' + pid
            return None

class UserDao(DaoBase):

    def __init__(self):
        DaoBase.__init__(self,"user")

    def save(self, user):
        doc = user.getDoc()
        uid = str(self.col.save(doc))
        return uid


#评论dao
class CommentDao(DaoBase):
    def __init__(self):
        DaoBase.__init__(self,"comment")

    #增加一条评论
    def add(self, comment):
        comment.cid = newCommentID()

        #将评论放到缓存中
        key = keyComment(comment.cid)
        val = json_encode(comment.__dict__)
        r.set(key, val)        

        #将评论放到mongo的队列
        #使用'comment_quque' 作为队列
        commentQueue = self.db['comment_queue']
        #确保status有索引
        if commentQueue.count() == 0:
            commentQueue.ensure_index([('status',pymongo.ASCENDING),('timestamp',pymongo.ASCENDING)])
        #status 0:普通，可以从队列弹出，1:删除，说明此数据已经出对
        t = time.time() * 1000 #获取当前时间毫秒数
        obj = {'comment':comment.__dict__,'timestamp':t,'status':0}        
        commentQueue.save(obj)        

    #删除一条评论
    def delete(self, cid):
        #从redis读取并更新
        key = keyComment(cid)
        cJson = r.get(key)
        if not cJson:
            return
        comment = json_decode(cJson)
        comment['stat'] = Comment.STAT_DEL
        r.set(key,json_encode(comment))

        #更新mongo库
        c = self.col.find({'cid':cid})
        c['stat'] = Comment.STAT_DEL
        self.col.save(c)





        

